import { Injectable, OnModuleInit } from "@nestjs/common";
import { breathConfig } from "../../../config";
import * as net from "node:net";

@Injectable()
export class MockSocketServerService implements OnModuleInit {
  server: net.Server;

  onModuleInit() {
    if (!breathConfig.openMockBreathServerFlag) {
      return;
    }
    console.log("MockSocket init");
    this.start();
  }

  start() {
    // 正弦信号参数
    const amplitude = 250; // 振幅
    const period = 3000; // 周期 (10秒)
    const sampleInterval = 20; // 采样间隔 (20毫秒)
    let startTime = null;
    const noiseLevel = 10;

    // 创建 TCP 服务器
    const server = net.createServer((socket) => {
      console.log("Client connected");

      startTime = process.hrtime.bigint();
      let lastExecutionTime = startTime;

      // 定期发送数据
      const sendSignal = () => {
        if (socket.destroyed) {
          return;
        }

        const currentTime = process.hrtime.bigint();
        const timeElapsed = Number(currentTime - startTime) / 1000000; // 转换为毫秒
        const actualInterval =
          Number(currentTime - lastExecutionTime) / 1000000; // 转换为毫秒
        lastExecutionTime = currentTime;

        // console.log(`Actual interval: ${actualInterval.toFixed(3)} ms`);

        const signalValue =
          amplitude * Math.sin((2 * Math.PI * timeElapsed) / period) +
          amplitude;
        const signalValue1 =
          amplitude * Math.sin((2 * Math.PI * timeElapsed) / (period * 2)) +
          amplitude;

        const multiValue = Number.parseInt(
          (signalValue + signalValue1).toFixed(0),
        );

        const buffer = new ArrayBuffer(4);
        const view = new Uint8Array(buffer);
        if (multiValue >= 256) {
          view[2] = Math.floor(multiValue / 256);
          view[3] = multiValue % 256;
        } else {
          view[2] = 0;
          view[3] = multiValue;
        }

        try {
          socket.write(view);
        }catch (e){
          console.log(`mock breath gather message send failed: ${e.message}`);
        }

        // 计算下一次发送的时间
        const nextSendTime =
          startTime +
          BigInt(
            Math.ceil(timeElapsed / sampleInterval) * sampleInterval * 1000000,
          );
        const delay = Number(nextSendTime - currentTime) / 1000000; // 转换为毫秒

        setTimeout(sendSignal, delay);
      };

      sendSignal();

      // 处理关闭事件
      socket.on("end", () => {
        console.log("Client disconnected");
      });

      // 处理错误事件
      socket.on("error", (err) => {
        console.error("Socket error:", err);
      });
    });

    // 服务器监听在指定端口
    const PORT = breathConfig.socketServerPort;
    server.listen(PORT, () => {
      console.log(`TCP server is running on port ${PORT}`);
    });
  }

  close() {
    this.server.close();
  }
}
